import 'dart:math';

import 'package:flutter/material.dart';

import '../common/api_service.dart';
import '../common/constants.dart';
import '../common/sharedPreferences_helper.dart';
import '../model/pipe_model.dart';
import '../utils/screen_util.dart';
import '../widgets/cartoon_list_view.dart';
import '../widgets/pipe_list_view.dart';
import '../widgets/user_list_view.dart';
import 'pipe_data_list_page.dart';

class SearchPage extends StatefulWidget {
  const SearchPage({super.key});

  @override
  State<SearchPage> createState() => _SearchPageState();
}

class _SearchPageState extends State<SearchPage> with SingleTickerProviderStateMixin {
  final TextEditingController _searchController = TextEditingController();
  final FocusNode _focusNode = FocusNode();
  final ScrollController _scrollController = ScrollController();
  TabController? _tabController;

  List<String> _historySearchList = [];
  late List<String> _searchHotwordList = [];
  final List<String> _hotwordList = [];
  final List<PipeModel> _pipeList = [];

  bool _isDeleteState = false;
  bool _isSearch = false;

  final List<String> _tabItemList = ['内容', '角色', '用户'];

  @override
  void initState() {
    super.initState();
    _scrollController.addListener(() {
      _focusNode.unfocus();
    });

    _getSearchHotwordList();
    _getRecommendPipeList();
    _getHistorySearchTextList();

    _tabController = TabController(length: _tabItemList.length, vsync: this);

    _focusNode.requestFocus();
  }

  void _getSearchHotwordList() {
    ApiService().getSearchHotWordList((list) {
      _hotwordList.clear();
      _hotwordList.addAll(list);
      setState(() {
        _searchHotwordList = _getRandomElements(_hotwordList, 6);
      });
    }, () {});
  }

  List<String> _getRandomElements(List<String> list, int count) {
    list.shuffle(Random());
    return list.take(count).toList();
  }

  void _getRecommendPipeList() {
    ApiService().getRecommendPipeList((list) {
      setState(() {
        _pipeList.clear();
        _pipeList.addAll(list);
      });
    }, () {});
  }

  void _getHistorySearchTextList() {
    var list = SharedPreferencesHelper.getStringList("SEARCH_WORD_LIST") ?? [];
    setState(() {
      _historySearchList = list;
    });
  }

  void _saveSearchWord(String word) {
    var list = SharedPreferencesHelper.getStringList("SEARCH_WORD_LIST") ?? [];
    if (list.contains(word)) {
      list.remove(word);
    }
    list.insert(0, word);
    SharedPreferencesHelper.setStringList("SEARCH_WORD_LIST", list);
    setState(() {
      _historySearchList = list;
      _isSearch = true;
    });
  }

  void _removeSearchHistoryWord(String word) {
    var list = SharedPreferencesHelper.getStringList("SEARCH_WORD_LIST") ?? [];
    if (list.contains(word)) {
      list.remove(word);
    }
    SharedPreferencesHelper.setStringList("SEARCH_WORD_LIST", list);
    setState(() {
      _historySearchList = list;
    });
  }

  void _deleteAllHistoryList() {
    SharedPreferencesHelper.setStringList("SEARCH_WORD_LIST", []);
    setState(() {
      _historySearchList = [];
    });
  }

  _buildChildList() {
    if (_isDeleteState) {
      return [
        const Text("历史记录"),
        const Spacer(),
        Padding(
            padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 2),
            child: InkWell(
                onTap: () {
                  _deleteAllHistoryList();
                },
                child: const Text("全部删除", style: TextStyle(color: Colors.black54)))),
        InkWell(
            onTap: () {
              setState(() {
                _isDeleteState = false;
              });
            },
            child: const Text("完成"))
      ];
    } else {
      return [
        const Text("历史记录"),
        const Spacer(),
        InkWell(
          onTap: () {
            setState(() {
              _isDeleteState = true;
            });
          },
          child: const Icon(
            Icons.delete_outline_outlined,
            color: Colors.black54,
          ),
        )
      ];
    }
  }

  _buildSearchHistory() {
    return _historySearchList.isEmpty
        ? Container()
        : Padding(
            padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 6),
            child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
              Row(
                children: _buildChildList(),
              ),
              Wrap(
                  spacing: 4.0,
                  runSpacing: -8,
                  children: List<Widget>.generate(
                    _historySearchList.length,
                    (int index) {
                      return _isDeleteState
                          ? InputChip(
                              side: const BorderSide(color: Color.fromRGBO(0, 0, 0, 0.08)),
                              backgroundColor: Colors.white,
                              labelStyle: const TextStyle(fontSize: 13, color: Color.fromRGBO(0, 0, 0, 0.71)),
                              padding: const EdgeInsets.all(0),
                              labelPadding: const EdgeInsets.fromLTRB(8, 0, 0, 0),
                              label: Text(_historySearchList[index]),
                              deleteIcon: const Icon(Icons.close, size: 20, color: Color.fromRGBO(0, 0, 0, 0.4)),
                              shape: RoundedRectangleBorder(
                                borderRadius: BorderRadius.circular(20.0),
                              ),
                              onSelected: (bool selected) {},
                              onDeleted: () {
                                setState(() {
                                  var text = _historySearchList[index];
                                  _removeSearchHistoryWord(text);
                                });
                              },
                            )
                          : ActionChip(
                              side: const BorderSide(color: Color.fromRGBO(0, 0, 0, 0.08)),
                              backgroundColor: Colors.white,
                              labelStyle: const TextStyle(fontSize: 13, color: Color.fromRGBO(0, 0, 0, 0.71)),
                              padding: const EdgeInsets.all(0),
                              labelPadding: const EdgeInsets.symmetric(horizontal: 10, vertical: 0),
                              label: Text(_historySearchList[index]),
                              shape: RoundedRectangleBorder(
                                borderRadius: BorderRadius.circular(20.0),
                              ),
                              onPressed: () {
                                var text = _historySearchList[index];
                                setState(() {
                                  _searchController.text = text;
                                });
                                _saveSearchWord(text);
                              },
                            );
                    },
                  ).toList()),
            ]),
          );
  }

  _buildBody(BuildContext context) {
    final screenWidth = ScreenUtil.getScreenWidth(context);
    var width = (screenWidth - 12.0) * 0.5;
    var height = width * 16 / 11;
    var h = height + 70;
    double ratio = width / h;

    if (_isSearch) {
      return _buildSearchList();
    }
    return GestureDetector(
        onTap: () {
          _focusNode.unfocus();
        },
        child: ListView.builder(
          controller: _scrollController,
          itemCount: 3,
          itemBuilder: (context, index) {
            switch (index) {
              case 0:
                return _buildSearchHistory();
              case 1:
                return Padding(
                  padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 6),
                  child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
                    Row(
                      children: [
                        const Text("猜你想搜"),
                        const Spacer(),
                        InkWell(
                          onTap: () {
                            setState(() {
                              _searchHotwordList = _getRandomElements(_hotwordList, 6);
                            });
                          },
                          child: const Icon(
                            Icons.autorenew,
                            color: Colors.black54,
                          ),
                        )
                      ],
                    ),
                    Wrap(
                        spacing: 4.0,
                        runSpacing: -8,
                        children: List<Widget>.generate(
                          _searchHotwordList.length,
                          (int index) {
                            return ActionChip(
                              side: const BorderSide(color: Color.fromRGBO(0, 0, 0, 0.08)),
                              backgroundColor: Colors.white,
                              labelStyle: const TextStyle(fontSize: 13, color: Color.fromRGBO(0, 0, 0, 0.71)),
                              padding: const EdgeInsets.all(0),
                              labelPadding: const EdgeInsets.symmetric(horizontal: 10, vertical: 0),
                              label: Text(_searchHotwordList[index]),
                              shape: RoundedRectangleBorder(
                                borderRadius: BorderRadius.circular(20.0),
                              ),
                              onPressed: () {
                                var text = _searchHotwordList[index];
                                setState(() {
                                  _searchController.text = text;
                                });
                                _saveSearchWord(text);
                              },
                            );
                          },
                        ).toList()),
                  ]),
                );
              case 2:
                return Padding(
                  padding: const EdgeInsets.fromLTRB(4, 4, 4, 0),
                  child: GridView.builder(
                    shrinkWrap: true,
                    physics: const NeverScrollableScrollPhysics(),
                    gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                      crossAxisCount: 2,
                      mainAxisSpacing: 0,
                      crossAxisSpacing: 4,
                      childAspectRatio: ratio,
                    ),
                    itemCount: _pipeList.length,
                    itemBuilder: (context, itemIndex) {
                      var pipe = _pipeList[itemIndex];
                      return HomePipeCard(width: width, height: height, pipe: pipe, showSummary: false);
                    },
                  ),
                );

              default:
                return const SizedBox.shrink();
            }
          },
        ));
  }

  _buildSearchList() {
    var text = _searchController.text.trim();
    return TabBarView(
        controller: _tabController,
        children: [
          PipeListView(searchText: text),
          CartoonListView(searchText: text),
          UserListView(searchText: text)
        ]
    );
  }

  @override
  void dispose() {
    _scrollController.dispose();
    _tabController?.dispose();
    _searchController.dispose();
    _focusNode.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      appBar: AppBar(
        backgroundColor: Colors.white,
        titleSpacing: 0,
        actions: [
          TextButton(
              onPressed: () {
                if (_searchController.text.trim().isNotEmpty) {
                  _saveSearchWord(_searchController.text.trim());
                }
              },
              child: const Text("搜索", style: TextStyle(fontSize: 16)))
        ],
        title: Container(
          height: 44,
          decoration: BoxDecoration(
            color: Colors.grey[200],
            borderRadius: BorderRadius.circular(8.0),
          ),
          child: TextField(
              cursorColor: Colors.blue,
              controller: _searchController,
              focusNode: _focusNode,
              decoration: const InputDecoration(
                  prefixIcon: Padding(
                    padding: EdgeInsets.fromLTRB(8, 0, 4, 0),
                    child: Icon(
                      Icons.search,
                      color: Colors.black38,
                      size: 24,
                    ),
                  ),
                  prefixIconConstraints: BoxConstraints(minWidth: 24, minHeight: 24),
                  hintText: '搜索内容/角色',
                  hintStyle: TextStyle(color: Colors.black38),
                  border: InputBorder.none,
                  contentPadding: EdgeInsets.symmetric(horizontal: 0, vertical: 11)),
              style: const TextStyle(fontSize: 16),
              onChanged: (query) {
                print('Search query: $query');
              },
              onSubmitted: (text) {
                print('Input completed: $text');
                if (text.trim().isNotEmpty) {
                  _saveSearchWord(text.trim());
                }
              }),
        ),
        bottom: _isSearch
            ? TabBar(
                controller: _tabController,
                tabAlignment: TabAlignment.start,
                isScrollable: true,
                indicatorColor: Constants.themeColor,
                indicatorSize: TabBarIndicatorSize.label,
                indicatorPadding: const EdgeInsets.symmetric(vertical: 3),
                labelPadding: const EdgeInsets.symmetric(horizontal: 10, vertical: 0),
                labelStyle: TextStyle(color: Constants.themeColor, fontWeight: FontWeight.w600),
                unselectedLabelStyle: const TextStyle(color: Colors.black54),
                dividerColor: Colors.grey[200],
                tabs: _tabItemList.map((data) => Tab(text: data)).toList(),
              )
            : null,
      ),
      body: _buildBody(context),
    );
  }
}
